package com.azt.back.action.quartz;

import com.azt.api.pojo.quartz.ScheduleJob;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoader;


public class QuartzJobFactory implements Job {

	private Logger log = LoggerFactory.getLogger(QuartzJobFactory.class);

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");
		try {
			invokMethod(scheduleJob);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void invokMethod(ScheduleJob scheduleJob) throws Exception {
		Object object = null;
		Class clazz = null;
		// springId不为空先按springId查找bean
		if (StringUtils.isNotBlank(scheduleJob.getJob_name())) {
			// object = SpringBeanFactory.getBean(scheduleJob.getJobName());
			object = ContextLoader.getCurrentWebApplicationContext().getBean(scheduleJob.getJob_name());
		} else if (StringUtils.isNotBlank(scheduleJob.getBean_class())) {
			clazz = Class.forName(scheduleJob.getBean_class());
			object = clazz.newInstance();
		}
		if (object == null) {
			log.error("任务名称 = [" + scheduleJob.getJob_name()+ "]---------------未启动成功，请检查是否配置正确！！！");
			return;
		}

		TaskInterface task = (TaskInterface) object;
		task.execute();
	}

}
